using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Ndo.FenCi
{
    public class Splitter : IFenCiProvider
    {
        public Splitter()
            :this(true)
        {}
        public Splitter(bool addDefaultSeparator)
        {
            if (addDefaultSeparator)
            {
                ucdict[System.Globalization.UnicodeCategory.LineSeparator] = null;
                ucdict[System.Globalization.UnicodeCategory.ParagraphSeparator] = null;
                ucdict[System.Globalization.UnicodeCategory.SpaceSeparator] = null;
            }
        }
        public string[] FenCi(string text)
        {
            List<string> ret = new List<string>();
            for (int i = 0; i < text.Length; )
            {
                int j = i;
                while (j<text.Length && !IsSeparator(text[j]))
                {
                    j++;
                }
                if (j != i)
                {
                    ret.Add(text.Substring(i, j - i));
                    i = j;
                }
                else
                {
                    i++;
                }
            }
            return ret.ToArray();
        }

        private Dictionary<char, object> chdict = new Dictionary<char, object>();
        private Dictionary<System.Globalization.UnicodeCategory, object> ucdict = new Dictionary<UnicodeCategory, object>();
        public void AddSeparatorCategory(System.Globalization.UnicodeCategory uc)
        {
            ucdict[uc] = null;            
        }

        public void AddSeparatorChar(char ch)
        {
            chdict[ch] = null;
        }
        public void AddSeparatorChars(params char[] chs)
        {
            foreach (char c in chs)
            {
                chdict[c] = null;
            }
        }

        protected virtual bool IsSeparator(char ch)
        {
            return chdict.ContainsKey(ch) || ucdict.ContainsKey(char.GetUnicodeCategory(ch));
        }
    }
}
